<?php

namespace pc\controllers;
use pc\models\News;
use pc\models\Portray;
use pc\models\Search;
use pc\models\Star;
use pc\models\Tags;
use Yii;
use pc\controllers\BaseController;

class SearchController extends BaseController
{
    //https://www.toutiao.com/search/?keyword=%E6%98%AD%E9%9B%84
    ///search/xxx/?keyword=xxx
    ///search/xxx/2.html?keyword=xxx
    ///search/xxx/3.html?keyword=xxx
    public function actionIndex(){

        Tags::randTags(10);

        $model = new Search();
        $model->load(Yii::$app->request->get());

        $typeMethod = [0 => 'all',1 => 'stars',2 => 'portrays',3 => 'news'];
        $typeUrl = [0 => '',1 => 'meinv',2 => 'xiezhen',3 => 'news'];

        $method = $typeMethod[$model->type];
        $url = $typeUrl[$model->type];

        $result = $model->$method();

        $recommend = false; //默认不推荐

        //结果为空的时候，随机推荐一点数据
        if(empty($result['data'])){
            if($model->type == Search::TYPE_ALL || $model->type == Search::TYPE_PORTRAY){
                //随机推荐点美女写真
                $result['data'] = Portray::randomPortrays(10,$model->portrayFields);
                if($model->type == Search::TYPE_ALL){
                    $result['data'] = array_map(function($value){
                        $value['searchType'] = Search::TYPE_PORTRAY;
                        return $value;
                    },$result['data']);
                }
            }else if($model->type == Search::TYPE_STAR){
                //随机推荐点美女
                $result['data'] = Star::randomStars(10,$model->starFields);
            }else if($model->type == Search::TYPE_NEWS){
                $result['data'] = News::randNews(10,$model->newsFields);
            }
            $recommend = true;
        }


        //设置分页数据
        $pagination = $result['pagination'];
        if(empty($url)){
            $pagination['formatUrl'] = "/search/{page}.html?keyword={$model->queryString}";
            $pagination['firstUrl'] = "/search/?keyword={$model->queryString}";
        }else{
            $pagination['formatUrl'] = "/search/{$url}/{page}.html?keyword={$model->queryString}";
            $pagination['firstUrl'] = "/search/{$url}/?keyword={$model->queryString}";
        }

        $pageString = $this->createPageString($pagination);

        //右侧明星总榜
        $stars = Star::getMaxViewStar(1,5,['id','name','nick_name','view','header'])['data'];

        return $this->render('index',[
           'data' => $result['data'],
           'queryString' => $model->queryString,
           'pageString' => $pageString,
           'searchType' => $model->type,
           'queryWords' => $model->queryWords,
           'stars' => $stars,
           'recommend' => $recommend,
           'page' => $model->currentPage,
        ]);
    }


}
